<template>
  <div class="login-container">
    <div>
      <div>
        <img :src="lang == 'zh-cn' ? contBg : contBgEn" alt="">
      </div>
      <section>
        <a-spin :spinning="loading">
          <div class="ft-size36 text-center">{{ lang == 'zh-cn' ? titleZh : titleEn}}{{ $t('other.intellHangerSystem') }}</div>
          <p class="ft-size16 text-center" v-if=" lang == 'zh-cn'">
            {{ titleEn }} INTELLIGENT HANGER SYSTEM
          </p>
          <a-form :model="formState" ref="formRef" @validateFields="handleOk" class="mt-40">
            <a-form-item
              name="username"
              :rules="[{ required: true, message: $t('layout.pleaseInputAccount') }]"
              class="relative"
            >
              <!-- <a-input v-model:value.trim="formState.username" placeholder="请输入账号" @keyup.enter="handleOk">
                <template #prefix>
                  <UserOutlined class="site-form-item-icon" />
                </template>
              </a-input> -->
              <span class="user-form-item-icon">
                <UserOutlined />
              </span>
              <a-auto-complete
                v-model:value.trim="formState.username"
                :options="loginUserList"
                :placeholder="$t('layout.pleaseInputAccount')"
              />
            </a-form-item>

            <a-form-item
              name="password"
              :rules="[{ required: true, message: $t('layout.pleaseInputPwd') }]"
            >
              <a-input-password
                v-model:value.trim="formState.password"
                :placeholder="$t('layout.pleaseInputPwd')"
                @keyup.enter="handleOk"
                autoComplete="new-password"
              >
                <template #prefix>
                  <LockOutlined />
                </template>
              </a-input-password>
            </a-form-item>

            <a-form-item>
              <a-button
                :disabled="disabled"
                @click="handleOk"
                type="brand"
                class="login-form-button"
                block
              >
                {{ $t('other.login') }}
              </a-button>
            </a-form-item>

            <!-- <div class="login-form-wrap">
              <a-form-item name="remember" no-style>
                <a-checkbox v-model:checked="remember">记住账号</a-checkbox>
              </a-form-item>
              <a-divider type="vertical" />
              <a class="primary-link">忘记密码</a>
            </div> -->
          </a-form>
        </a-spin>
      </section>
    </div>
  </div>
</template>

<script setup name="enteyLogin">
import { ref, computed, onBeforeMount } from "vue";
import { UserOutlined, LockOutlined } from "@ant-design/icons-vue";
import axios from "@/utils/request";
import { useRouter } from "vue-router";
import { getLocalStorage } from "@/utils";
import { findIndex, cloneDeep } from "lodash"; 
let contBg = require(process.env.VUE_APP_LOGIN_BG)
let contBgEn = require(process.env.VUE_APP_LOGIN_BG_EN)
const router = useRouter();
let loading = ref(false);
const formState = ref({
  username: "",
  password: "",
});
const titleZh = process.env.VUE_APP_LOGIN_CN;
const titleEn = process.env.VUE_APP_LOGIN_EN;
const formRef = ref();
let lang = ref('')
// const remember = ref(false)
let loginUserList = ref([]);
const setUserList = () => {
  let userlist = [...loginUserList.value];
  if (findIndex(userlist, (i) => i.value == formState.value.username) == -1) {
    userlist.push({ value: formState.value.username });
    localStorage.setItem("loginUserList", JSON.stringify(userlist));
  }
};
const handleOk = async () => {
  try {
    const values = await formRef.value.validateFields();
    loading.value = true;
    const res = await axios.postAction("/api/login", values);
    loading.value = false;
    if (res.success) {
      localStorage.setItem("unlocakPage", 0);
      localStorage.setItem("lockModalVisible", 0);
      const { accessToken, menuList, buttonMenuList,  user, hangerLineList, autoScreenLockTime, configVO, } = res.data;
      setUserList();
      localStorage.setItem("token", accessToken);
      menuList && getPermissionMenu(menuList);
      buttonMenuList &&
        localStorage.setItem("buttonMenuList", JSON.stringify(buttonMenuList));
      localStorage.setItem("user", JSON.stringify(user));
      localStorage.setItem("configuration", JSON.stringify(configVO));
      localStorage.setItem("autoScreenLockTime", Number(autoScreenLockTime));
      localStorage.setItem("sortingFinishedProductIn", Number(configVO?.sortingFinishedProductIn || 0));
      // localStorage.setItem( "allowMaxOverproduction",  Number(allowMaxOverproduction) ); // 允许最大超产数

      if (hangerLineList) {
        localStorage.setItem("hangerLineList", JSON.stringify(hangerLineList));
        localStorage.setItem( "currentLine", JSON.stringify(hangerLineList[0] || {}) )
        localStorage.setItem("currentLineStatus",JSON.stringify(hangerLineList[0].status || false))
      } else {
        localStorage.setItem("currentLine", JSON.stringify({}));
      }
      let path =
        process.env.VUE_APP_CONFIG == "online"
          ? "/makeManage/makeList"
          : "/hangManage/prodTimeInfo";
      console.log(path, 'path');
      router.replace({ path: path });
    }
  } catch (err) {
    console.log("🚀 ~ file: enteyLogin.vue:139 ~ handleOk ~ err:", err)
    loading.value = false;
  }
};
const getPermissionMenu = (menuList) => {
  let menu = cloneDeep(menuList);
  if (process.env.VUE_APP_CONFIG == "local") {
    /*menu.forEach(i => {
      //不显示 本地自动排产
      if (i.id == '1551755550620000000') {
        console.log(i)
        i.children = i.children.filter(
          ei => {
            // return !['1551755550620217000','1551755550621500000'].includes(ei.id)
            return !['自动排产'].includes(ei.label)
          }
        )
      }
    })*/
  } else if (process.env.VUE_APP_CONFIG == "online") {
    // 不展示 [系统管理->消息管理、配置项]
    menu.forEach((i) => {
      if (i.id == "1551755550640000000") {
        i.children = i.children.filter(
          (el) =>
            !["1551755550640700000", "1551755550640800000"].includes(el.id)
        );
      }
    });
    // 不展示 [吊挂管理->自动排产、排产单、排产单管理、产线实时信息、历史排产单、衣架查询、衣架明细、目标产量管理]
    menu.forEach((i) => {
      if (i.id == "1551755550620000000") {
        i.children = i.children.filter(
          (el) =>
            ![
              "1551755550621100000",
              "1551755550621700000",
              "1551755550621500000",
              "1551755550621800000",
              "1551755550621900000",
              "1551755550622000000",
              "1551755550622100000",
              "1551755550622200000",
            ].includes(el.id)
        );
      }
    });
  } else {
    console.log("吊挂");
    //生产资料大类删除了 暂时隐藏
    // menu.forEach(i => {
    //   //生产资料不显示 本地自动排产     自动排产：1551755550620223000  排产单：1551755550620218000
    //   if (i.id == '1551755550620000000') {
    //     i.children.filter(
    //       el => {
    //         el.children = el.children.filter(
    //           ei => {
    //             return !['1551755550620222000', '1551755550620217000', '1551755550620212000','1551755550620223000','1551755550620218000'].includes(ei.id)
    //           }
    //         )
    //       }
    //     )
    //   }
    // })
  }
  localStorage.setItem("menu", JSON.stringify(menu));
};
const disabled = computed(() => {
  return !(formState.value.username && formState.value.password);
});
onBeforeMount(() => {
  lang.value = localStorage.getItem("locale") || 'zh-cn'
  loginUserList.value = getLocalStorage("loginUserList") || [];
});
</script>